package com.sojson.controller.po;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sojson.config.exception.TransErrorCode;
import com.sojson.controller.po.param.verify.RoleParamVerify;
import com.sojson.entity.po.Menu;
import com.sojson.entity.po.Role;
import com.sojson.result.Result;
import com.sojson.service.MenuService;
import com.sojson.service.RoleService;
import com.sojson.util.StringUtil;
import com.sojson.util.token.TokenUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 角色信息表控制器
 * 
 * @author liu
 * @date 2021-04-13
 */
@Api(tags = "角色信息表管理")
@RestController
@RequestMapping(value = "/role")
public class RoleController {

    @Resource
    private RoleService roleServiceImpl;
    @Autowired
    private MenuService menuService;

    /**
     * 单条插入
     * 
     * @param role
     * @return
     * @throws SQLException
     */
    @PostMapping("/insert")
    @PreAuthorize("@ss.hasPermi('/role/insert')")
    @ApiOperation(value = "添加角色", response = int.class)
    public Object insert(@RequestBody Role role) throws SQLException {
        // 校验参数
        Result<?> paramResult = RoleParamVerify.insert(role);
        // 验证不通过
        if (!paramResult.getCode().equals(TransErrorCode.SUCCESS.getCode())) {
            return paramResult;
        }

        role.insertInit();
        return Result.success(roleServiceImpl.insert(role));
    }

    /**
     * 批量插入
     * 
     * @param role
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/insertList", method = RequestMethod.POST)
    public Object insertList(@RequestBody Role role) throws SQLException {
        return Result.success(roleServiceImpl.insertList(role));
    }

    /**
     * 通过对象批量删除(物理删除)
     * 
     * @param role
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/deleteByDto", method = RequestMethod.POST)
    public Object deleteByDto(@RequestBody Role role) throws SQLException {
        return Result.success(roleServiceImpl.deleteByDto(role));
    }

    /**
     * 统计全部数量
     * 
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/countAll", method = RequestMethod.GET)
    public Object countAll() throws SQLException {
        int countAll = roleServiceImpl.countAll();
        return Result.success(countAll);
    }

    /**
     * 查询所有
     * 
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/findAll", method = RequestMethod.GET)
    public Object findAll() throws SQLException {
        List<Role> findAll = roleServiceImpl.findAll();
        return Result.success(findAll);
    }

    /**
     * 根据对象统计数量
     * 
     * @param role
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/countByDto", method = RequestMethod.POST)
    public Object countByDto(@RequestBody Role role) throws SQLException {
        int countByDto = roleServiceImpl.countByDto(role);
        return Result.success(countByDto);
    }

    /**
     * 根据对象查询
     * 
     * @param role
     * @return
     * @throws SQLException
     */
    @GetMapping("/findByDto")
    @PreAuthorize("@ss.hasPermi('/role/findByDto')")
    @ApiOperation(value = "通过对象查询角色", response = Role.class)
    public Object findByDto(Role role) throws SQLException {
        String keysStr = role.getKeysStr();
        if (StringUtil.isNotBlankString(keysStr)) {
            role.setKeys(Arrays.asList(keysStr.split(",")));
        }
        List<Role> findByDto = roleServiceImpl.findByDto(role);
        return Result.success(findByDto, findByDto);
    }

    /**
     * 通过id删除(物理删除)
     * 
     * @param id
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    public Object deleteById(Integer id) throws SQLException {
        roleServiceImpl.deleteById(id);
        return Result.success();
    }

    /**
     * 通过id列表删除(物理删除)
     * 
     * @param ids
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/deleteByIdList", method = RequestMethod.POST)
    public Object deleteByIdList(@RequestParam("ids[]") ArrayList<Integer> ids) throws SQLException {
        return Result.success(roleServiceImpl.deleteByIdList(ids));
    }

    /**
     * 通过id更新(全部更新)
     * 
     * @param role
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/updateById", method = RequestMethod.POST)
    public Object updateById(@RequestBody Role role) throws SQLException {
        roleServiceImpl.updateById(role);
        return Result.success();
    }

    /**
     * 通过id列表更新(全部更新)(更新内容相同)
     * 
     * @param role
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/updateStaticByIdList", method = RequestMethod.POST)
    public Object updateStaticByIdList(@RequestBody Role role) throws SQLException {
        return Result.success(roleServiceImpl.updateStaticByIdList(role));
    }

    /**
     * 通过id列表更新(全部更新)(更新内容不相同)
     * 
     * @param role
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/updateChangeByIdList", method = RequestMethod.POST)
    public Object updateChangeByIdList(@RequestBody Role role) throws SQLException {
        return Result.success(roleServiceImpl.updateChangeByIdList(role));
    }

    /**
     * 通过id更新(局部更新)
     * 
     * @param role
     * @return
     * @throws Exception 
     */
    @PutMapping(value = "/updatePartialById")
    @PreAuthorize("@ss.hasPermi('/role/updatePartialById')")
    @ApiOperation(value = "通过ID修改角色和角色菜单关联关系", response = int.class)
    public Object updatePartialById(@RequestBody Role role) throws Exception {
        // 校验参数
        Result<?> paramResult = RoleParamVerify.updatePartialById(role);
        // 验证不通过
        if (!paramResult.getCode().equals(TransErrorCode.SUCCESS.getCode())) {
            return paramResult;
        }

        if (role.getId() != 2) {
            return Result.fail("暂时只能修改普通管理员！");
        }
        role.updateInit();
        role.setUpdateNull();
        return Result.success(roleServiceImpl.updatePartialById(role));
    }

    /**
     * 修改保存数据权限
     */
    @PutMapping("/dataScope")
    @PreAuthorize("@ss.hasPermi('/role/dataScope')")
    @ApiOperation(value = "通过ID修改角色和角色部门关联关系", response = int.class)
    public Object dataScope(@RequestBody Role role) {
        // 校验参数
        Result<?> paramResult = RoleParamVerify.updatePartialById(role);
        // 验证不通过
        if (!paramResult.getCode().equals(TransErrorCode.SUCCESS.getCode())) {
            return paramResult;
        }

        role.updateInit();
        role.setUpdateNull();
        return Result.success(roleServiceImpl.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @PutMapping("/changeStatus")
    @PreAuthorize("@ss.hasPermi('/role/changeStatus')")
    @ApiOperation(value = "修改角色状态", response = int.class)
    public Object changeStatus(@RequestBody Role role) {
        Integer id = role.getId();
        if (StringUtil.isBlankObject(role)) {
            return Result.fail("角色ID不能为空！");
        }
        Integer status = role.getStatus();
        if (StringUtil.isBlankObject(role)) {
            return Result.fail("角色状态不能为空！");
        }

        Role ro = new Role();
        ro.setId(id);
        ro.setStatus(status);
        return Result.success(roleServiceImpl.updateRoleStatus(ro));
    }

    /**
     * 删除角色
     * @throws SQLException 
     */
    @DeleteMapping("/deleteRoleByIds/{ids}")
    @PreAuthorize("@ss.hasPermi('/role/deleteRoleByIds/{ids}')")
    @ApiOperation(value = "通过角色ID数组删除角色", response = int.class)
    @ApiImplicitParams({@ApiImplicitParam(name = "ids", value = "角色ID数组")})
    public Object remove(@PathVariable Integer[] ids) throws SQLException {
        return Result.success(roleServiceImpl.deleteRoleByIds(ids));
    }

    /**
     * 通过id列表更新(局部更新)(更新内容相同)
     * 
     * @param role
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/updateStaticPartialByIdList", method = RequestMethod.POST)
    public Object updateStaticPartialByIdList(@RequestBody Role role) throws SQLException {
        return Result.success(roleServiceImpl.updateStaticPartialByIdList(role));
    }

    /**
     * 通过id列表更新(局部更新)(更新内容不相同)
     * 
     * @param role
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/updateChangePartialByIdList", method = RequestMethod.POST)
    public Object updateChangePartialByIdList(@RequestBody Role role) throws SQLException {
        return Result.success(roleServiceImpl.updateChangePartialByIdList(role));
    }

    /**
     * 通过id查询
     * 
     * @param id
     * @return
     * @throws SQLException
     * @throws IOException 
     */
    @GetMapping("/findById")
    public Object findById(Integer id) throws SQLException, IOException {
        List<Menu> menus = menuService.selectMenuList(TokenUtil.getUserId());
        Map<Object, Object> hashMap = new HashMap<>();
        hashMap.put("role", roleServiceImpl.findById(id));
        hashMap.put("checkedKeys", menuService.selectMenuListByRoleId(id));
        hashMap.put("menus", menuService.buildMenuTreeSelect(menus));
        return Result.success(hashMap);
    }

    /**
     * 通过id列表查询
     * 
     * @param ids
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/findByIdList", method = RequestMethod.GET)
    public Object findByIdList(@RequestParam("ids[]") ArrayList<Integer> ids) throws SQLException {
        ArrayList<Role> findByIdList = roleServiceImpl.findByIdList(ids);
        return Result.success(findByIdList);
    }

    /**
     * 通过对象查询id列表
     * 
     * @param role
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/findIdByDto", method = RequestMethod.POST)
    public Object findIdByDto(@RequestBody Role role) throws SQLException {
        ArrayList<Integer> findIdByDto = roleServiceImpl.findIdByDto(role);
        return Result.success(findIdByDto);
    }

    /**
     * 通过对象删除(逻辑删除)
     * 
     * @param role
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/deleteByDtoAndUpdate", method = RequestMethod.POST)
    public Object deleteByDtoAndUpdate(@RequestBody Role role) throws SQLException {
        return Result.success(roleServiceImpl.deleteByDtoAndUpdate(role));
    }

    /**
     * 统计所有未删除的数据
     * 
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/countAllAndStatusNo", method = RequestMethod.GET)
    public Object countAllAndStatusNo() throws SQLException {
        int countAllAndStatusNo = roleServiceImpl.countAllAndStatusNo();
        return Result.success(countAllAndStatusNo);
    }

    /**
     * 查询所有未删除的数据
     * 
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/findAllAndStatusNo", method = RequestMethod.GET)
    public Object findAllAndStatusNo() throws SQLException {
        ArrayList<Role> findAllAndStatusNo = roleServiceImpl.findAllAndStatusNo();
        return Result.success(findAllAndStatusNo);
    }

    /**
     * 通过id删除(逻辑删除)
     * 
     * @param id
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/deleteByIdAndUpdate", method = RequestMethod.POST)
    public Object deleteByIdAndUpdate(Integer id) throws SQLException {
        roleServiceImpl.deleteByIdAndUpdate(id);
        return Result.success();
    }

    /**
     * 通过id列表删除(逻辑删除)
     * 
     * @param ids
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/deleteByIdListAndUpdate", method = RequestMethod.POST)
    public Object deleteByIdListAndUpdate(@RequestParam("ids[]") ArrayList<Integer> ids) throws SQLException {
        return Result.success(roleServiceImpl.deleteByIdListAndUpdate(ids));
    }

    /**
     * 清空数据(物理清空)
     * 
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/clear", method = RequestMethod.POST)
    public Object clear() throws SQLException {
        roleServiceImpl.clear();
        return Result.success();
    }

    /**
     * 清空数据(逻辑清空)
     * 
     * @return
     * @throws SQLException
     */
    // @RequestMapping(value = "/clearAndUpdate", method = RequestMethod.POST)
    public Object clearAndUpdate() throws SQLException {
        roleServiceImpl.clearAndUpdate();
        return Result.success();
    }

    /**
     * 获取角色选择框列表
     * @throws SQLException 
     */
    @GetMapping("/optionselect")
    @PreAuthorize("@ss.hasPermi('/role/optionselect')")
    @ApiOperation(value = "获取角色选择框列表", response = Role.class)
    public Object optionselect() throws SQLException {
        return Result.success(roleServiceImpl.selectRoleAll());
    }

}